package com.ruoyi.project.system.third.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint("/soap/{requestId}")
@Component
public class WebSocketServer {
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static final AtomicInteger onlineNum = new AtomicInteger();

    /**
     * 存放每个客户端对应的WebSocketServer对象
     */
    private static final ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    /**
     * 发送消息
     *
     * @param session 会话
     * @param message 消息
     * @throws IOException IO异常
     */
    public void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 给指定用户发送信息
     *
     * @param requestId 请求id
     * @param message   信息
     */
    public void sendInfo(String requestId, String message) {
        Session session = sessionPools.get(requestId);
        try {
            sendMessage(session, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断请求是否存在
     *
     * @param requestId 请求id
     */
    public boolean exist(String requestId) {
        Session session = sessionPools.get(requestId);
        return session != null;
    }


    /**
     * 建立连接成功调用
     *
     * @param session   会话
     * @param requestId 请求id
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "requestId") String requestId) {
        sessionPools.put(requestId, session);
        addOnlineCount();
        log.info("{}加入webSocket！当前人数为{}", requestId, onlineNum);
        try {
            sendMessage(session, "欢迎" + requestId + "加入连接！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 关闭连接时调用
     *
     * @param requestId 请求id
     */
    @OnClose
    public void onClose(@PathParam(value = "requestId") String requestId) {
        sessionPools.remove(requestId);
        subOnlineCount();
        log.info("{}断开webSocket连接！当前请求数为{}", requestId, onlineNum);
    }


    /**
     * 收到客户端信息
     *
     * @param message 消息
     */
    @OnMessage
    public void onMessage(String message) {
        message = "客户端：" + message + ",已收到";
        log.info(message);
        for (Session session : sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("websocket发生错误，当前为{}，错误原因：{}", session.getId(), throwable.getMessage());
    }

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
}
